import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Image,
  Dimensions,
  TouchableOpacity,
} from 'react-native';
import LoopSwiper from './LoopSwiper';
const { width } = Dimensions.get('window');
export default class Home extends Component {
  static navigationOptions = {
    headerTitle: '首页',
  };
  state = {
    newslist: [],
    refreshing: false,
  }
  componentDidMount () {
    this.getListData();
  }
  getListData = async () => {
    try {
      this.setState({
        refreshing: true
      })
      const res = await fetch('http://api.tianapi.com/nba?key=c732ed00482b7208218faf599e32239a&num=30');
      const resJson = await res.json(); // promise对象要用await接收
      const { code, newslist = [] }  = resJson;
      if (code === 200) {
        const mapArr = newslist.map((item, index) => ({
          key: index.toString(),
          ...item
        }));
        this.setState({
          newslist: mapArr,
          refreshing: false
        });
      }
    } catch (error) {
      console.log('error', error);
      this.setState({ refreshing: false });
    }
  }
  handleDetail = (item) => {
    this.props.navigation.push('homeDetail', {
      url: item.url
    });
  }
  renderListItem = (listItem) => {
    const { item = {} } = listItem;
    return (
      <TouchableOpacity
        key={item.key}
        activeOpacity={0.5}
        onPress={this.handleDetail.bind(this, item)}
      >
        <View style={styles.listItem}>
          <Image style={styles.leftImg} source={{ uri: item.picUrl }} />
          <View style={styles.rightContent}>
            <Text>{item.title}</Text>
            <Text style={styles.description}>{item.description} {item.ctime}</Text>
          </View>
        </View>
      </TouchableOpacity>
    )
  }
  render() {
    const { newslist, refreshing } = this.state;
    return (
      <View style={styles.homePage}>
        <View style={styles.loopBox}>
          <LoopSwiper />
        </View>
        <FlatList
            data={newslist}
            renderItem={this.renderListItem}
            refreshing={refreshing}
            onRefresh={this.getListData}
          />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  homePage: {
    flex: 1,
    alignItems: 'center'
  },
  loopBox: {
    height: 160
  },
  listItem: {
    width: width,
    flexDirection: 'row',
    paddingLeft: 5,
    paddingRight: 5,
    paddingTop: 5,
    paddingBottom: 5,
    borderBottomWidth: 1,
    borderBottomColor: '#eee'
  },
  leftImg: {
    width: 50,
    height: 50,
    marginRight: 10
  },
  rightContent: {
    flex: 1
  },
  description: {
    color: '#bbb',
    marginTop: 5,
    fontSize: 12
  }
})
